package com.aote.component.format;

import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.browsesoft.ExtendElement;
import com.browsesoft.PropertiesService;

public class FormatFactory {
	/**
	 * 缓存的格式处理器
	 */
	private Map formats = new HashMap();

	/**
	 * 单列
	 */
	private static FormatFactory self = new FormatFactory();

	public static FormatFactory getInstance() {
		return self;
	}

	private FormatFactory() {
		load();
	}

	/**
	 * 根据属性文件配置，加载格式处理器
	 */
	private void load() {
		NodeList nl = PropertiesService.getDocument().getElementsByTagName(
				"formatter");
		for (int i = 0; i < nl.getLength(); i++) {
			Element e = (Element) nl.item(i);
			// 根据类名构造对象
			String name = e.getAttribute("name");
			String className = e.getAttribute("class");
			try {
				Formatter form = (Formatter) Class.forName(className)
						.newInstance();
				this.formats.put(name, form);
			} catch (InstantiationException e1) {
				throw new RuntimeException("不可以实例化：" + className);
			} catch (IllegalAccessException e1) {
				throw new RuntimeException("不可以访问：" + className);
			} catch (ClassNotFoundException e1) {
				throw new RuntimeException("类找不到：" + className);
			}
		}
	}

	/**
	 * 执行格式化过程，调用每一个格式处理器处理
	 */
	public String format(String string, Element config) {
		String s = string;
		// 让每一个格式处理器进行处理
		Iterator iter = formats.keySet().iterator();
		while (iter.hasNext()) {
			String key = (String) iter.next();
			Formatter f = (Formatter) this.formats.get(key);
			s = f.format(s, config);
		}
		return s;
	}

	/**
	 * silverlight format
	 */
	public String formatOfSilvr(String formatObj, String formatExp) {
		String[] strs = formatExp.split(";");
		for (int i = 0; i < strs.length; i++) {
			if (formatObj == null || formatObj.equals("")) {
				continue;
			}
			String oneFormat = strs[i];
			String formatName = "";
			String formatParam = "";
			//如果有()
			if (oneFormat.indexOf("(") != -1) {
				formatName = oneFormat.substring(0,oneFormat.indexOf("("));
				formatParam = oneFormat.substring(oneFormat.indexOf("(")+1,
						oneFormat.indexOf(")"));
			} 
			//没有()，说明无参数   
            else {
				formatName = oneFormat;
			}
			Formatter formatter = (Formatter) this.formats.get(formatName);
			if(formatter == null)
			{
			   continue;
			}
			formatObj = formatter.formatOfSilver(formatObj, formatParam);
		}
		return formatObj;
	}

	public static void format(Element form, Map map) {
		Iterator iter;
		// 进行格式处理
		iter = ExtendElement.findElementsOfAttr(form, "fieldtype").iterator();
		while (iter.hasNext()) {
			Element e = (Element) iter.next();
			String name = e.getAttribute("name");
			String value = (String) map.get(name);
			// 对值进行格式化
			if (value == null) {
				continue;
			}
			value = FormatFactory.getInstance().format(value, e);
			map.put(name, value);
		}
	}
}
